package com.geoai.uimap.core.mapbox

import com.geoai.basiclib.utils.log.MyLogUtils
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.plugins.annotation.Fill
import com.mapbox.mapboxsdk.plugins.annotation.FillOptions
import com.mapbox.mapboxsdk.plugins.annotation.Line
import com.mapbox.mapboxsdk.plugins.annotation.LineOptions
import com.mapbox.mapboxsdk.utils.ColorUtils
import com.geoai.uimap.api.IGEOMap
import com.geoai.uimap.api.GEOMapCircle
import com.geoai.uimap.geo.Point
import com.geoai.uimap.geo.SimpleProjection
import com.geoai.uimap.utils.MathUtils
import com.geoai.uimap.utils.getMapBoxGeometry

class MapboxCircle(private val map: IGEOMap) : GEOMapCircle() {

    private var mFill: Fill? = null

    //Polygon的边界
    private var mLine: Line? = null

    override fun show(): GEOMapCircle {
        if (centerPoint == null) return this
        val mapBoxManager = map.getMapBoxGeometry() ?: return this
        val fillManager = mapBoxManager.getFillManager()
        if (fillManager == null) {
            MyLogUtils.d("fillManager 为空")
            return this
        }

        val simpleProjection = SimpleProjection(centerPoint) //基点
        val preTurnFirstPoint = simpleProjection.GeoPoint2Point(centerPoint)
        val preTurnFirstMathPoint: MathUtils.Point =
                MathUtils.Point(preTurnFirstPoint.x, preTurnFirstPoint.y)
        val circleOnAftTurn: MathUtils.Circle = MathUtils.Circle()
        circleOnAftTurn.center.x = preTurnFirstPoint.x
        circleOnAftTurn.center.y = preTurnFirstPoint.y
        circleOnAftTurn.radius = mRadius

        val allPoints = mutableListOf<LatLng>()
        var startAngle = 0.0
        while (startAngle <= 360.0) {
            val p = MathUtils.getPointOnCircle(circleOnAftTurn, Math.toRadians(startAngle))
            val midPoint = simpleProjection.Point2GeoPoint(Point(p.x, p.y))
            allPoints.add(LatLng(midPoint.latitude, midPoint.longitude))
            startAngle += 3.0
        }

        val latLngs: MutableList<List<LatLng>> = ArrayList()
        latLngs.add(allPoints)
        val fillOptions = FillOptions()
                .withLatLngs(latLngs)
                .withFillColor(ColorUtils.colorToRgbaString(mColor))
                .withFillOutlineColor(ColorUtils.colorToRgbaString(mStrokeColor))
        mFill = fillManager.create(fillOptions)

        val lineManager = mapBoxManager.getLineManager()
        lineManager?.let {
            val lineOptions = LineOptions()
                    .withLatLngs(allPoints)
                    .withLineColor(ColorUtils.colorToRgbaString(mStrokeColor))
                    .withLineWidth(mStrokeWidth)
            mLine = lineManager.create(lineOptions)
        }

        return this
    }

    override fun destroy() {
        mFill?.let {
            map.getMapBoxGeometry()?.getFillManager()?.delete(it)
        }
        mLine?.let {
            map.getMapBoxGeometry()?.getLineManager()?.delete(it)
        }
    }


}